﻿<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<meta http-equiv="X-UA-Compatible" content="ie=edge">
	<title>Document</title>
	<link rel="stylesheet" href="lib/bootstrap-3.3.7.css">
	<script type="text/javascript" src="lib/vue-2.4.0.js"></script>
</head>
<body>
	<div id="app">
		<!-- 发表评论框 -->
		<cmt-box @func="loadComments"></cmt-box>
		<!-- 评论列表 -->
		<ul class="list-group">
			<li class="list-group-item" v-for="item in list" :key="item.id">
				<span class="badge">评论人：{{item.user}}</span>
				{{item.content}}
			</li>
		</ul>
	</div>
	<!-- 评论框模板 -->
	<template id="temp1">
		<div>
			<div class="form-group">
				<label>评论人：</label>
				<input type="text" class="form-control" v-model="user">
			</div>
			<div class="form-group">
				<label>评论内容：</label>
				<textarea class="form-control" v-model="content"></textarea>
			</div>
			<div class="form-group">
				<input type="button" value="发表评论" class="btn btn-primary" @click="postComment">
			</div>
		</div>
	</template>
	<script>
	var commentBox = {
		template: '#temp1',
		data(){
			return {
				user: '',
				content: ''
			}
		},
		methods: {
			postComment(){
				var comment = { id: Date.now(), user: this.user, content: this.content };
				if ( this.user == '' && this.content == '' ) {
					alert( '评论人不能为空' );
					return false;
				}
				// 在提交诗句之前先获取 localStorage 上的数据
				var list = JSON.parse( localStorage.getItem( 'cmts' ) || '[]' );
				list.unshift( comment );
				localStorage.setItem( 'cmts' , JSON.stringify(list) );
				this.user = this.content = '';
				this.$emit('func');
			}
		}
	}
	// 创建 Vue 实例，得到 ViewModel
	var  vm = new Vue({
		el: '#app',
		data: {
			list: [
				{ id : Date.now(), user: '李白', content: '天生我材必有用' },
				{ id : Date.now(), user: '红袖', content: '天生我材必有用1' },
				{ id : Date.now(), user: '江白', content: '天生我材必有用2' }
			]
		},
		created(){
			this.loadComments();
		},
		methods: {
			loadComments(){
				var list = JSON.parse( localStorage.getItem( 'cmts' ) || '[]' );
				this.list = list;
			}
		},
		components: {
			'cmt-box' : commentBox
		}
	});
	</script>

</body>
</html>